! function ($) {

  $(function () {

    class glass {
      constructor() {

        //登录 和 退出
        this.login = $(".login");//登录
        this.register = $(".register");//注册
        this.tuichu = $(".tuichu");//退出

      }

      moverLoading () {
        let cookid = []; //存放商品的编号数组
        let cooknum = []; //存放商品的数量数组

        function cook () {   //将cookie值取出转换成数组，利用数组进行判断是否是第一次
          if (cookie.get('cookiesid') && cookie.get('cookienum')) {  //判断有没有值
            cookid = cookie.get('cookiesid').split(',');//cookie存放商品编号的key值
            cooknum = cookie.get('cookienum').split(',');//cookie存放商品价格的key值
          }
        }

        $(".num>input").on("change", function () {
          var $reg = /^\d+$/g; //只能输入数字
          var $value = parseInt($(this).val());
          if ($reg.test($value)) {//是数字
            if ($value >= 99) {//限定范围
              $(this).val(99);
            } else if ($value <= 0) {
              $(this).val(1);
            } else {
              $(this).val($value);
            }
          } else {//不是数字
            $(this).val(1);
          }
          let $intid = $(this).parents(".details-product").find(".bigimg-pics li").eq(0).find('img').attr("sid");
          cook();
          cooknum[$.inArray($intid, cookid)] = $(this).parents(".details-product").find(".num>input").val();
          cookie.set('cookienum', cooknum.toString(), 10);
        })


        $(".cartbox").on("click", function () {
          let $sid = $(this).parents(".details-product").find(".bigimg-pics li").eq(0).find('img').attr("sid");
          cook();

          if ($.inArray($sid, cookid) !== -1) {//不等于-1 就是存在cookie值 说明之前已经存过了
            //$.inArray($sid,cookid)  取当前点击的商品编号 在cookid数组中的 下标位置
            //cooknum[$.inArray($sid,cookid)]    以$.inArray($sid,cookid)为下标  取对应商品id的cooknum值

            let change = parseInt(cooknum[$.inArray($sid, cookid)]) + parseInt($("#buyNum").val());
            //change就是取出之前存入cookie的值  然后加上 新加上的购物商品数量  2者数量相加

            cooknum[$.inArray($sid, cookid)] = change;//把新的数量总值  重新赋值给对应商品id的cooknum值

            cookie.set('cookienum', cooknum.toString(), 10); //然后 存入cookie  改变cooknum值  此时 cooknum值就是旧的数量加新的数量的总和
          } else {//等于-1  就是没找到    也就是cookie值不存在  说明之前没存过
            cookid.push($sid);   //将编号推进数组
            cookie.set('cookiesid', cookid.toString(), 10);  ///因为cookid是一个数组 所以不能用JSON.stringify方法存 JSON.stringify方法只是针对对象(json对象)的形式 
            cooknum.push($("#buyNum").val());
            cookie.set('cookienum', cooknum.toString(), 10);
          }
        })
      }

      init () {
        var _this = this;
        $(document).ready(function () {
          _this.id = sessionStorage.getItem("goodId");
          _this.ajax1();
        })
      }

      ajax1 () {
        var _this = this;
        $.ajax({
          url: "http://localhost:3000/goods",
          type: "GET",
          dataType: "json",
          success: function (arr) {
            console.log(arr)
            var str = "";
            for (var i = 0; i < arr.length; i++) {
              if (String(arr[i].id) === _this.id) {
                str = `<div class="details-center clear">
              <!-- 顶部标题开始 -->
              <div class="detail-crumb detail-center" id="samCrumb">
                <a href="../html/shoue.html">首页<i class="iconfont">&#xe7d3;</i></a>
                <a><span class="crumb-span1"></span><i class="iconfont">&#xe7d3;</i></a>
                <a><span class="crumb-span2"></span><i class="iconfont">&#xe7d3;</i></a>
                <a><span class="crumb-span3"></span><i class="iconfont">&#xe7d3;</i></a>
                <a><span class="crumb-span4"></span><i class="iconfont">&#xe7d3;</i></a>
                <a class="blue crumb-a5" href=""></a>
              </div>
              <!-- 顶部标题结束 -->
        
              <!-- 商品详情开始 -->
              <div class="details-product clear">
                <!-- 放大镜部分开始 -->
                <div class="details-commodit clear">
                  <!-- 小图 -->
                  <div class="pro-img clear">
                    <div class="bigimg clear">
                      <ul class="bigimg-pics">
                        <li class="active glass-li1">
                            <img src="${arr[i].detailsImg1}" alt="">
                        </li>
                        <li class="glass-li2">
                            <img src="${arr[i].detailsImg2}" alt="">
                        </li>
                        <li class="glass-li3">
                            <img src="${arr[i].detailsImg3}" alt="">
                        </li>
        
        
                        <div class="small-move"></div>
                      </ul>
        
        
        
                    </div>
                    <div id="bigf">
                      <!-- 大图 -->
                      <img src="${arr[i].detailsImg1}" alt="" id="bigpic">
                    </div>
        
                  </div>
        
                  <!-- 左边的小盒子列表 -->
                  <div class="smallimg">
                    <div class="smallimgbox">
                      <ul class="smallimgbox-trig" style="height: 532px; width: 65px; top: 0px; left: 0px;">
                        <li class="cur glass-li1">
                          <img src="${arr[i].detailsImg1}" alt="">
                        </li>
                        <li class="glass-li2">
                          <img src="${arr[i].detailsImg2}" alt="">
        
                        </li>
                        <li class="glass-li3">
                          <img src="${arr[i].detailsImg3}" alt="">
                        </li>
                      </ul>
        
                    </div>
        
                    <a class="btn-up iconfont" href="javascript:;">&#xe685;</a>
                    <a class="btn-down iconfont" href="javascript:;">&#xe506;</a>
        
                  </div>
        
        
                </div>
                <!-- 放大镜部分结束 -->
        
        
                <!-- 商品信息开始 -->
                <div class="details-message" style="width: 636px;">
        
                  <div class="details-title">
                    <p id="cnName" class="title-box is-tags-mark i-size-tit">
                      <u class="pro-tag jsd-tag"></u>
                      <span></span>
                    </p>
                    <p class="subtitle"></p>
        
                    <div class="price" style="margin-bottom: 0;">
                      <span class="pricenum">
                        <sub>¥${arr[i].price}</sub>
                        <del id="mainprice"></del>
                        <!-- 降价通知 -->
                        <em class="thePrice" id="sam_priceNotice">降价通知</em>
                      </span>
                      <span class="weight" id="mainweight">重量：<em>${arr[i].zhongliang}</em></span>
                    </div>
        
        
                    <div class="promotional" id="promotion" style="">
                      <div class="open" id="promOpenBtn">
                        <a class="show iconfont" href="javascript:;">&#xe633;</a>
                        <a class="hide iconfont" href="javascript:;">&#xe64f;</a>
                      </div>
                      <dl class="fullcoupon clear">
                        <dt>满购返券</dt>
                        <dd>指定商品购满199元返20元优惠券，每人最高可参与1次</dd>
                        <dd>指定商品购满388元返40元优惠券，每人最高可参与1次</dd>
                      </dl>
                    </div>
        
                    <div id="favorableRateDom" class="praise">
                      <i class="icons iconfont">&#xe577;</i>
                      <u id="favorableRate">${arr[i].dianZanNum}</u>的用户给出好评
                    </div>
        
        
                    <div class="address clear" id="samDeliveryAddress">
                      <div class="icons iconfont">&#xe5b0;</div>
                      <div class="addressCon">
                        <span class="zhi">送货至</span>
                        <div class="selectbox pcTreeBox" id="pcTreeBox">
                          <div class="yhd_province clearfix">
                            <div class="yhd_area_select">
                              <div class="yhd_address">
                                <span class="yhd_val_text">${arr[i].songHuoZhi}</span>
                              </div>
                            </div>
                          </div>
                        </div>
                        <span class="color" id="stockstatus" style="">${arr[i].shangPingZhuanTai}</span><span id="deliveryMsg"
                          style="">,11:20前下单,预计09月03日 11:30-12:30送达</span>
                      </div>
                      <p id="deliverMap" class="maps" style="">
                        仅配送
                        <a class="" href="javascript:;">
                          指定区域
                          <u class="iconfont">&#xe606;</u>
                        </a></p>
                    </div>
        
        
        
                    <div class="tags">
                      <i class="icons iconfont">&#xe603;</i>
                      <a href="">${arr[i].shangPingZhuanTai}</a>
                    </div>
        
        
                    <!-- 加入购物车开始 -->
                    <div class="coomon-cart">
                      <!-- 加减开始 -->
                      <div class="numbers" id="numAddcart">
                        <div id="reduceBtn" class="reduce iconfont">&#xe64f;</div>
                        <div class="num">
                          <input id="buyNum" data-max="999999" data-min="1" data-step="1" type="text" value="1">
                        </div>
                        <div id="addBtn" class="add iconfont">&#xe633;</div>
                      </div>
        
        
                      <!-- 加减结束 -->
        
                      <div class="cartbox buy_btn1 clear" id="addCart" style="">
                        <a href="javascript:;" class="cart-atr">
                          <i class="iconfont">&#xe608;</i>
                          <span style="color: #ffffff;">加入购物车</span>
        
                        </a>
                      </div>
        
        
                      <div class="btns">
                        <span class="collection buy_btn2">
                          <i class="iconfont">&#xe604;</i>常购清单
                        </span>
                        <span class="share">
                          <i class="iconfont">&#xe621;</i>分享
                        </span>
                      </div>
        
        
                      <div class="payment">
                        <a href="javascript:;">支付方式</a>
                        <ul class="clear payment-ul">
                          <li><i class="icon1"></i>支付宝</li>
                          <li><i class="icon2"></i>银行转账</li>
                          <li><i class="icon3"></i>货到付款</li>
                          <li><i class="icon4"></i>银联支付</li>
                          <li><i class="icon5"></i>沃尔玛购物卡</li>
                          <li class="tips" style="width: 100%;">以结算页信息为准</li>
                        </ul>
                      </div>
        
        
        
                    </div>
                    <!-- 加入购物车结束 -->
        
                  </div>
        
                </div>
                <!-- 商品信息结束 -->
        
        
                <!-- 弹窗效果 开始-->
                <div id="cart-tan" class="white-cart">
                  <div class="cart-wrap">
                    <div class="cart-header">
                      <a href="javascript:;" class="iconfont cart-close">&#xe618;</a>
                    </div>
                    <div class="cart-content">
                      <p class="cart-shan">商品已成功加入购物车</p>
                    </div>
                    <div class="clear cart-btn">
                      <a href="../html/cart.html" class="cart-ok">查看购物车</a>
                      <a href="javascript:;" class="cart-cancel">继续购物</a>
                    </div>
        
        
                  </div>
        
                </div>
                <div id="cart-beijin" class="black-cart">
                </div>
        
                <!-- 弹窗效果 结束 -->        
              </div>
            </div>`
              }
            }

            $("#detailsContent").html(str)
            _this.yuansu()
            _this.othere();
            _this.moverLoading();
          }
        })
      }

      yuansu () {
        this.bigimg_pics = $(".bigimg-pics");//6张小图的父级元素 ul
        this.bigli = $(".bigimg-pics li");//每张li标签的合集
        this.small_move = $(".small-move");//小放大镜
        this.bigf = $("#bigf")//大放大镜
        this.bigpic = $("#bigpic")//大图
        this.pro = $(".pro-img");//ul的父级元素

        //放大镜左边的图片
        this.smallimgbox = $(".smallimgbox-trig li");//
        this.smallimgbox_ul = $(".smallimgbox-trig");
        this.btn_up = $(".btn-up");//上 
        this.btn_down = $(".btn-down");//下

        //购物车的加减运算
        this.addBtn = $("#addBtn");//加号
        this.reduceBtn = $("#reduceBtn");//减号
        this.buyNum = $("#buyNum");//input里的值

        //购物车的弹窗效果
        this.cart_atr = $(".cart-atr")//购物车按钮
        this.cart_tan = $("#cart-tan")//弹窗
        this.cart_beijin = $("#cart-beijin")//弹窗的背景
        this.cart_close = $(".cart-close")//弹窗的x按钮
        this.cart_ok = $(".cart-ok")//弹窗的确定按钮
        this.cart_cancel = $(".cart-cancel")//弹窗的取消按钮
      }

      othere () {
        let _this = this;
        // console.log(this.addBtn);

        if (localStorage.getItem('customname')) { //如果有isLogin 那么说明登录成功 因为isLogin是和用户名同时存的 当做判断条件存的 没其他意义
          this.login.html(localStorage.getItem('customname'));
          this.register.hide();

        } else {
          this.tuichu.hide();
        }

        this.tuichu.on("click", function () {
          localStorage.removeItem('customname');  //删除本地存储
          location.reload();//刷新页面
        })

        this.bigimg_pics.hover(function () {
          $('.small-move,#bigf').css('visibility', 'visible');
          // _this.small_move.css("visibility",'visible');
          // _this.bigf.css("visibility",'visible');

          _this.bigimg_pics.on("mousemove", function (ev) {//鼠标移动时
            _this.movebox(ev);

          })


        }, function () {
          $('.small-move,#bigf').css('visibility', 'hidden');
          // _this.small_move.css("visibility",'hidden');
          // _this.bigf.css("visibility",'hidden');

        })

        this.liwidth = this.bigli.eq(0).width();
        this.liheight = this.bigli.eq(0).height();
        //小放大镜的宽度     小放/小图=大放/大图  小放=小图*大放/大图 
        //求小放的尺寸   小放/小图=大放/大图  用visibility隐藏元素   尺寸可以单独拿出来写 否则使用display要放在hover的事件里
        this.small_move.css({
          width: this.liwidth * this.bigf.width() / this.bigpic.width(),
          height: this.liheight * this.bigf.height() / this.bigpic.height()
        })

        //比例计算   比例计算 可以是大图/小图  也可以是大放大镜/小放大镜
        this.bili = this.bigpic.width() / this.liwidth;


        //左边图片的代码
        this.smallimgbox.on("mouseover", function () {
          let int = $(this).index();
          let $imgurl = $(this).find("img").attr("src");
          $(this).addClass("cur").siblings().removeClass("cur");
          _this.bigpic.attr('src', $imgurl);
          _this.bigli.eq(int).addClass("active").siblings().removeClass("active");


        })

        //左边图片的下箭头
        this.num = 6;
        this.smallimgboxliHeight = this.smallimgbox.eq(0).outerHeight();
        this.btn_down.on("click", function () {
          if (_this.smallimgbox.length > _this.num) {
            _this.num++;
            _this.smallimgbox_ul.stop(true).animate({
              top: -_this.smallimgboxliHeight * (_this.num - 6)
            }, 500)
          }
        })
        //左边图片的上箭头
        this.btn_up.on("click", function () {
          if (_this.num > 6) {
            _this.num--;
            _this.smallimgbox_ul.stop(true).animate({
              top: -_this.smallimgboxliHeight * (_this.num - 6)
            }, 500)
          }

        })


        // this.addBtn=$("#addBtn");//加号
        // this.reduceBtn=$("#reduceBtn");//减号
        // this.buyNum=$("#buyNum");//input里的值

        //购物车的加减运算
        let com = 1;
        this.addBtn.on("click", function () {
          com++;
          _this.buyNum.val(com);

        })

        this.reduceBtn.on("click", function () {
          if (_this.buyNum.val() > 1) {
            com--;
            _this.buyNum.val(com);

          }

        })



        //购物车的弹窗效果            
        this.cart_atr.on("click", function () {//点击加入购物车 出现弹窗
          _this.num1 = $('#buyNum').val()
          _this.addbut()
          // var obj = [{"id":_this.id,"nums":this.num}]
          // console.log(obj);
          // var obj1 = JSON.stringify(obj)
          // console.log(obj1);
          // 购物车件数
          _this.addcar1 = localStorage.getItem("addcar") ? JSON.parse(localStorage.getItem("addcar")) : [];
          _this.carnum2 = 0;
          for (var i = 0; i < _this.addcar1.length; i++) {
            console.log(typeof parseInt(_this.addcar1[i].nums));
            console.log(typeof parseInt(_this.carnum2));


            _this.carnum2 = parseInt(_this.carnum2) + parseInt(_this.addcar1[i].nums);
          }
          $("#carnum").text(_this.carnum2);

          _this.cart_tan.css('display', 'block');
          _this.cart_beijin.css('display', 'block');
        })

        this.cart_close.on("click", function () {//取消弹窗
          _this.cart_tan.css('display', 'none');
          _this.cart_beijin.css('display', 'none');
        })

        this.cart_cancel.on("click", function () {//取消弹窗
          _this.cart_tan.css('display', 'none');
          _this.cart_beijin.css('display', 'none');
        })
      }

      addbut () {
        var arr = localStorage.getItem("addcar") ? JSON.parse(localStorage.getItem("addcar")) : [];
        // console.log(arr);
        // console.log(_this.id);

        if (arr.length === 0) {
          arr.push({
            id: this.id,
            nums: this.num1
          })
          // console.log(arr);
        } else {
          var t1 = 1;
          for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == this.id) {
              // console.log(_this.id);
              // console.log(arr[i].id);
              var butnum = parseInt(this.num1);
              var kienum = parseInt(arr[i].nums);
              arr[i].nums = butnum + kienum
              t1 = 0;
            }
          }
          if (t1 == 1) {
            arr.push({
              id: this.id,
              nums: this.num1
            })
          }
        }
        localStorage.setItem("addcar", JSON.stringify(arr));
      }

      movebox (ev) {
        let l = ev.pageX - this.pro.offset().left - this.small_move.width() / 2;//jquery的pageX和pageY属性 就相当于原生dom的ev.clientX和ev.clientY
        let t = ev.pageY - this.pro.offset().top - this.small_move.height() / 2;
        if (l < 0) {//判定边界
          l = 0
        } else if (l >= this.bigimg_pics.width() - this.small_move.width()) {
          l = this.bigimg_pics.width() - this.small_move.width()
        }

        if (t < 0) {//判定边界
          t = 0
        } else if (t >= this.bigimg_pics.height() - this.small_move.height()) {
          t = this.bigimg_pics.height() - this.small_move.height()
        }
        this.bigpic.css({
          left: -l * this.bili,//根据小放移动的距离再乘以两者的比例 比如比例是2倍(大图宽800，小图宽400，两者的比例就是2倍) 小放移动50 那大放往相反的方向移动100
          top: -t * this.bili
        })
        this.small_move.css({
          left: l,
          top: t
        })
      }
    }
    new glass().init();
  })
}(jQuery);